package tcp;

/**
 * Created by lizhun on 16/6/15.
 */

import com.nativetalk.common.SpringConfig;
import com.nativetalk.service.live.LiveService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

public class HelloServer {

    /*
     * 创建服务端监听端口
     */

    private static final int portNumber = 9999;
    public static void main(String[] args) throws InterruptedException {
        //配置服务器Nio线程组
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
            // For the destroy method to work.
            ctx.registerShutdownHook();

            LiveService liveService = (LiveService) ctx.getBean("liveService");
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boosGroup, workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new HelloServerInitializer())
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6);
            bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(640, 10240, 655360));
            //服务器绑定端口监听
            ChannelFuture channelFuture = bootstrap.bind(portNumber).sync();
            //监听服务器关闭监听
            channelFuture.channel().closeFuture().sync();
            System.out.println("启动成功");
        }finally{
            //退出时释放资源
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}